<?php
/**
 * 获取当前登录的管事员id
 * @return int
 */
function get_current_admin_id(){
	return session('ADMIN_ID');
}

/**
 * 获取当前登录的管事员id
 * @return int
 */
function jsd_get_current_admin_id(){
	return session('ADMIN_ID');
}

/**
 * 判断前台用户是否登录
 * @return boolean
 */
function jsd_is_user_login(){
    $session_user=session('user');
	return !empty($session_user);
}

/**
 * 获取当前登录的前台用户的信息，未登录时，返回false
 * @return array|boolean
 */
function jsd_get_current_user(){
    $session_user=session('user');
	if(!empty($session_user)){
		return $session_user;
	}else{
		return false;
	}
}

/**
 * 更新当前登录前台用户的信息
 * @param array $user 前台用户的信息
 */
function jsd_update_current_user($user){
	session('user',$user);
}

/**
 * 获取当前登录前台用户id,推荐使用jsd_get_current_userid
 * @return int
 */
function get_current_userid(){
	$session_user_id=session('user.user_id');
	if(!empty($session_user_id)){
		return $session_user_id;
	}else{
		return 0;
	}
}

/**
 * 获取当前登录前台用户id
 * @return int
 */
function jsd_get_current_userid(){
	return get_current_userid();
}

/**
 * 返回带协议的域名
 */
function jsd_get_host(){
	$host=$_SERVER["HTTP_HOST"];
	$protocol=is_ssl()?"https://":"http://";
	return $protocol.$host;
}

/**
 * 获取用户头像相对网站根目录的地址
 */
function jsd_get_user_avatar_url($avatar){

	if($avatar){
		if(strpos($avatar, "http")===0){
			return $avatar;
		}else {
		    if(strpos($avatar, 'avatar/')===false){
		        $avatar='avatar/'.$avatar;
		    }
		    $url =  jsd_get_asset_upload_path($avatar,false);
		    if(C('FILE_UPLOAD_TYPE')=='Qiniu'){
		        $storage_setting=jsd_get_jsd_settings('storage');
		        $qiniu_setting=$storage_setting['Qiniu']['setting'];
		        $filepath=$qiniu_setting['protocol'].'://'.$storage_setting['Qiniu']['domain']."/".$avatar;
		        if($qiniu_setting['enable_picture_protect']){
		            $url = $url.$qiniu_setting['style_separator'].$qiniu_setting['styles']['avatar'];
		        }
		    }
		    
			return $url;
		}

	}else{
		return $avatar;
	}
}

/**
 * JSD密码加密方法
 * @param string $pw 要加密的字符串
 * @return string
 */
function jsd_password_admin($pw,$authcode=''){
    if(empty($authcode)){
        $authcode=C("AUTHCODE");
    }
	$result="###".md5(md5($authcode.$pw));
	return $result;
}

/**
 * JSD密码加密方法 (X2.0.0以前的方法)
 * @param string $pw 要加密的字符串
 * @return string
 */
function jsd_password_old($pw){
    $decor=md5(C('DB_PREFIX'));
    $mi=md5($pw);
    return substr($decor,0,12).$mi.substr($decor,-4,4);
}

/**
 * 密码比较方法,所有涉及密码比较的地方都用这个方法
 * @param string $password 要比较的密码
 * @param string $password_in_db 数据库保存的已经加密过的密码
 * @return boolean 密码相同，返回true
 */
function jsd_compare_password($password,$password_in_db){
    if(strpos($password_in_db, "###")===0){
        return jsd_password($password)==$password_in_db;
    }else{

        return jsd_password_old($password)==$password_in_db;
    }
}

/**
 * 随机字符串生成
 * @param int $len 生成的字符串长度
 * @return string
 */
function jsd_random_string($len = 6) {
	$chars = array(
			"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
			"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
			"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
			"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
			"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
			"3", "4", "5", "6", "7", "8", "9"
	);
	$charsLen = count($chars) - 1;
	shuffle($chars);    // 将数组打乱
	$output = "";
	for ($i = 0; $i < $len; $i++) {
		$output .= $chars[mt_rand(0, $charsLen)];
	}
	return $output;
}

/**
 * 清空系统缓存，兼容sae
 */
function jsd_clear_cache(){
		import ( "ORG.Util.Dir" );
		$dirs = array ();
		// runtime/
		$rootdirs = jsd_scan_dir( RUNTIME_PATH."*" );
		//$noneed_clear=array(".","..","Data");
		$noneed_clear=array(".","..");
		$rootdirs=array_diff($rootdirs, $noneed_clear);
		foreach ( $rootdirs as $dir ) {

			if ($dir != "." && $dir != "..") {
				$dir = RUNTIME_PATH . $dir;
				if (is_dir ( $dir )) {
					//array_push ( $dirs, $dir );
					$tmprootdirs = jsd_scan_dir ( $dir."/*" );
					foreach ( $tmprootdirs as $tdir ) {
						if ($tdir != "." && $tdir != "..") {
							$tdir = $dir . '/' . $tdir;
							if (is_dir ( $tdir )) {
								array_push ( $dirs, $tdir );
							}else{
								@unlink($tdir);
							}
						}
					}
				}else{
					@unlink($dir);
				}
			}
		}
		$dirtool=new \Dir("");
		foreach ( $dirs as $dir ) {
			$dirtool->delDir ( $dir );
		}

		if(jsd_is_sae()){
			$global_mc=@memcache_init();
			if($global_mc){
				$global_mc->flush();
			}

			$no_need_delete=array("THINKJSD_DYNAMIC_CONFIG");
			$kv = new SaeKV();
			// 初始化KVClient对象
			$ret = $kv->init();
			// 循环获取所有key-values
			$ret = $kv->pkrget('', 100);
			while (true) {
				foreach($ret as $key =>$value){
                    if(!in_array($key, $no_need_delete)){
                    	$kv->delete($key);
                    }
                }
				end($ret);
				$start_key = key($ret);
				$i = count($ret);
				if ($i < 100) break;
				$ret = $kv->pkrget('', 100, $start_key);
			}

		}
}

/**
 * 更新系统配置文件
 * @param array $data <br>如：array("URL_MODEL"=>0);
 * @return boolean
 */
function jsd_set_dynamic_config($data){
	if(!is_array($data)){
		return false;
	}

	if(jsd_is_sae()){
		$kv = new SaeKV();
		$ret = $kv->init();
		$configs=$kv->get("THINKJSD_DYNAMIC_CONFIG");
		$configs=empty($configs)?array():unserialize($configs);
		$configs=array_merge($configs,$data);
		$result = $kv->set('THINKJSD_DYNAMIC_CONFIG', serialize($configs));
	}elseif(defined('IS_BAE') && IS_BAE){
		$bae_mc=new BaeMemcache();
		$configs=$bae_mc->get("THINKJSD_DYNAMIC_CONFIG");
		$configs=empty($configs)?array():unserialize($configs);
		$configs=array_merge($configs,$data);
		$result = $bae_mc->set("THINKJSD_DYNAMIC_CONFIG",serialize($configs),MEMCACHE_COMPRESSED,0);
	}else{
		$config_file="./data/conf/config.php";
		if(file_exists($config_file)){
			$configs=include $config_file;
		}else {
			$configs=array();
		}
		$configs=array_merge($configs,$data);
		$result = file_put_contents($config_file, "<?php\treturn " . var_export($configs, true) . ";");
	}
	jsd_clear_cache();
	S("jsd_dynamic_config",$configs);
	return $result;
}

/**
 * 去除字符串中的指定字符
 * @param string $str 待处理字符串
 * @param string $chars 需去掉的特殊字符
 * @return string
 */
function jsd_strip_chars($str, $chars='?<*.>\'\"'){
	return preg_replace('/['.$chars.']/is', '', $str);
}

/**
 * 字符串复杂加密、解密封装详细
 * @param string $string
 */
function jsd_authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;

	$key = md5($key ? $key : C("AUTHCODE"));
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

/**
 * 字符串复杂加密、解密封装
 * @param string $string
 */
function jsd_authencode($string){
	return jsd_authcode($string,"ENCODE");
}

/**
 * 获得字符串相对路径
 * @param string $url 待处理url
 * @return string
 */
function jsd_get_relative_url($url){
	if(strpos($url,"http")===0){
		$url=str_replace(array("https://","http://"), "", $url);

		$pos=strpos($url, "/");
		if($pos===false){
			return "";
		}else{
			$url=substr($url, $pos+1);
			$root=preg_replace("/^\//", "", __ROOT__);
			$root=str_replace("/", "\/", $root);
			$url=preg_replace("/^".$root."\//", "", $url);
			return $url;
		}
	}
	return $url;
}

/**
 * 判断是否为手机访问
 * @return  boolean
 */
function jsd_is_mobile() {
	static $jsd_is_mobile;

	if ( isset($jsd_is_mobile) )
		return $jsd_is_mobile;

	if ( empty($_SERVER['HTTP_USER_AGENT']) ) {
		$jsd_is_mobile = false;
	} elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.)
			|| strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
			|| strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
			|| strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
			|| strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
			|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
			|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false ) {
		$jsd_is_mobile = true;
	} else {
		$jsd_is_mobile = false;
	}

	return $jsd_is_mobile;
}

/**
 * 判断是否为微信访问
 * @return boolean
 */
function jsd_is_weixin(){
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}

/**
 * 处理插件钩子
 * @param string $hook   钩子名称
 * @param mixed $params 传入参数
 * @return void
 */
function hook($hook,$params=array()){
	tag($hook,$params);
}

/**
 * 处理插件钩子,只执行一个
 * @param string $hook   钩子名称
 * @param mixed $params 传入参数
 * @return void
 */
function hook_one($hook,$params=array()){
    return \Think\Hook::listen_one($hook,$params);
}


/**
 * 获取插件类的类名
 * @param strng $name 插件名
 */
function jsd_get_plugin_class($name){
	$class = "plugins\\{$name}\\{$name}Plugin";
	return $class;
}

/**
 * 获取插件类的配置
 * @param string $name 插件名
 * @return array
 */
function jsd_get_plugin_config($name){
	$class = jsd_get_plugin_class($name);
	if(class_exists($class)) {
		$plugin = new $class();
		return $plugin->getConfig();
	}else {
		return array();
	}
}

/**
 * 替代scan_dir的方法
 * @param string $pattern 检索模式 搜索模式 *.txt,*.doc; (同glog方法)
 * @param int $flags
 */
function jsd_scan_dir($pattern,$flags=null){
	$files = array_map('basename',glob($pattern, $flags));
	return $files;
}

/**
 * 获取所有钩子，包括系统，应用，模板
 */
function jsd_get_hooks($refresh=false){
	if(!$refresh){
		$return_hooks = F('all_hooks');
		if(!empty($return_hooks)){
			return $return_hooks;
		}
	}

	$return_hooks=array();
	$system_hooks=array(
		"url_dispatch","app_init","app_begin","app_end",
		"action_begin","action_end","module_check","path_info",
		"template_filter","view_begin","view_end","view_parse",
		"view_filter","body_start","footer","footer_end","sider","comment",'admin_home'
	);

	$app_hooks=array();

	$apps=jsd_scan_dir(SPAPP."*",GLOB_ONLYDIR);
	foreach ($apps as $app){
		$hooks_file=SPAPP.$app."/hooks.php";
		if(is_file($hooks_file)){
			$hooks=include $hooks_file;
			$app_hooks=is_array($hooks)?array_merge($app_hooks,$hooks):$app_hooks;
		}
	}

	$tpl_hooks=array();

	$tpls=jsd_scan_dir("themes/*",GLOB_ONLYDIR);

	foreach ($tpls as $tpl){
		$hooks_file= jsd_add_template_file_suffix("themes/$tpl/hooks");
		if(file_exists_case($hooks_file)){
			$hooks=file_get_contents($hooks_file);
			$hooks=preg_replace("/[^0-9A-Za-z_-]/u", ",", $hooks);
			$hooks=explode(",", $hooks);
			$hooks=array_filter($hooks);
			$tpl_hooks=is_array($hooks)?array_merge($tpl_hooks,$hooks):$tpl_hooks;
		}
	}

	$return_hooks=array_merge($system_hooks,$app_hooks,$tpl_hooks);

	$return_hooks=array_unique($return_hooks);

	F('all_hooks',$return_hooks);
	return $return_hooks;

}


/**
 * 生成访问插件的url
 * @param string $url url 格式：插件名://控制器名/方法
 * @param array $param 参数
 */
function jsd_plugin_url($url, $param = array(),$domain=false){
	$url        = parse_url($url);
	$case       = C('URL_CASE_INSENSITIVE');
	$plugin     = $case ? parse_name($url['scheme']) : $url['scheme'];
	$controller = $case ? parse_name($url['host']) : $url['host'];
	$action     = trim($case ? strtolower($url['path']) : $url['path'], '/');

	/* 解析URL带的参数 */
	if(isset($url['query'])){
		parse_str($url['query'], $query);
		$param = array_merge($query, $param);
	}

	/* 基础参数 */
	$params = array(
			'_plugin'     => $plugin,
			'_controller' => $controller,
			'_action'     => $action,
	);
	$params = array_merge($params, $param); //添加额外参数

	return U('api/plugin/execute', $params,true,$domain);
}

/**
 * 检查权限
 * @param name string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
 * @param uid  int           认证用户的id
 * @param relation string    如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
 * @return boolean           通过验证返回true;失败返回false
 */
function jsd_auth_check($uid,$name=null,$relation='or'){
	if(empty($uid)){
		return false;
	}

	$iauth_obj=new \Common\Lib\iAuth();
	if(empty($name)){
		$name=strtolower(MODULE_NAME."/".CONTROLLER_NAME."/".ACTION_NAME);
	}
	return $iauth_obj->check($uid, $name, $relation);
}

/**
 * 验证码检查，验证完后销毁验证码增加安全性 ,<br>返回true验证码正确，false验证码错误
 * @return boolean <br>true：验证码正确，false：验证码错误
 */
function check_verify_code($verifycode=''){
    $verify = new \Think\Verify();
	return $verify->check($verifycode, 1);
}

/**
 * 手机验证码检查，验证完后销毁验证码增加安全性 ,<br>返回true验证码正确，false验证码错误
 * @return boolean <br>true：手机验证码正确，false：手机验证码错误
 */
function jsd_check_mobile_verify_code($mobile='',$verifycode=''){
    $session_mobile_code=session('mobile_code');
    $verifycode= empty($verifycode)?I('request.mobile_code'):$verifycode;
    $mobile= empty($mobile)?I('request.mobile'):$mobile;
    
    $result= false;
    
    if(!empty($session_mobile_code) && $session_mobile_code['code'] == md5($mobile.$verifycode.C('AUTHCODE')) && $session_mobile_code['expire_time']>time()){
        $result = true;
    }
    
    return $result;
}

/**
 * 插件R方法扩展 建立多插件之间的互相调用。提供无限可能
 * 使用方式 get_plugns_return('Chat://Index/index',array())
 * @param string $url 调用地址
 * @param array $params 调用参数
 * @author 5iymt <1145769693@qq.com>
 */
function jsd_get_plugins_return($url, $params = array()){
	$url        = parse_url($url);
	$case       = C('URL_CASE_INSENSITIVE');
	$plugin     = $case ? parse_name($url['scheme']) : $url['scheme'];
	$controller = $case ? parse_name($url['host']) : $url['host'];
	$action     = trim($case ? strtolower($url['path']) : $url['path'], '/');

	/* 解析URL带的参数 */
	if(isset($url['query'])){
		parse_str($url['query'], $query);
		$params = array_merge($query, $params);
	}
	return R("plugins://{$plugin}/{$controller}/{$action}", $params);
}

/**
 * 判断模板文件是否存在，区分大小写
 * @param string $file 模板文件路径，相对于当前模板根目录，不带模板后缀名
 */
function jsd_template_file_exists($file){
    $theme= jsd_get_current_theme();
    $filepath=C("jsd_TMPL_PATH").$theme."/".$file;
    $tplpath = jsd_add_template_file_suffix($filepath);

    if(file_exists_case($tplpath)){
        return true;
    }else{
        return false;
    }

}

/**
 * 判断当前的语言包，并返回语言包名
 */
function jsd_check_lang(){
    $langSet = C('DEFAULT_LANG');
    if (C('LANG_SWITCH_ON',null,false)){

        $varLang =  C('VAR_LANGUAGE',null,'l');
        $langList = C('LANG_LIST',null,'zh-cn');
        // 启用了语言包功能
        // 根据是否启用自动侦测设置获取语言选择
        if (C('LANG_AUTO_DETECT',null,true)){
            if(isset($_GET[$varLang])){
                $langSet = $_GET[$varLang];// url中设置了语言变量
                cookie('think_language',$langSet,3600);
            }elseif(cookie('think_language')){// 获取上次用户的选择
                $langSet = cookie('think_language');
            }elseif(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){// 自动侦测浏览器语言
                preg_match('/^([a-z\d\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches);
                $langSet = $matches[1];
                cookie('think_language',$langSet,3600);
            }
            if(false === stripos($langList,$langSet)) { // 非法语言参数
                $langSet = C('DEFAULT_LANG');
            }
        }
    }

    return strtolower($langSet);

}

/**
* 删除图片物理路径
* @param array $imglist 图片路径
* @return bool 是否删除图片
* @author 高钦 <395936482@qq.com>
*/
function jsd_delete_physics_img($imglist){
    $file_path = C("UPLOADPATH");

    if ($imglist) {
        if ($imglist['thumb']) {
            $file_path = $file_path . $imglist['thumb'];
            if (file_exists($file_path)) {
                $result = @unlink($file_path);
                if ($result == false) {
                    $res = TRUE;
                } else {
                    $res = FALSE;
                }
            } else {
                $res = FALSE;
            }
        }

        if ($imglist['photo']) {
            foreach ($imglist['photo'] as $key => $value) {
                $file_path = C("UPLOADPATH");
                $file_path_url = $file_path . $value['url'];
                if (file_exists($file_path_url)) {
                    $result = @unlink($file_path_url);
                    if ($result == false) {
                        $res = TRUE;
                    } else {
                        $res = FALSE;
                    }
                } else {
                    $res = FALSE;
                }
            }
        }
    } else {
        $res = FALSE;
    }

    return $res;
}

/**
 * 安全删除位于头像文件夹中的头像
 *
 * @param string $file 头像文件名,不含路径
 * @author rainfer <81818832@qq.com>
 */
function jsd_delete_avatar($file)
{
    if($file){
		$file='data/upload/avatar/'.$file;
		if (\Think\Storage::has($file)) {
			\Think\Storage::unlink($file);
		}
	}
}

/**
 * 获取惟一订单号
 * @return string
 */
function jsd_get_order_sn(){
    return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

/**
 * 获取文件扩展名
 * @param string $filename
 */
function jsd_get_file_extension($filename){
    $pathinfo=pathinfo($filename);
    return strtolower($pathinfo['extension']);
}

/**
 * 检查手机是否还可以发送手机验证码,并返回生成的验证码
 * @param string $mobile
 */
function jsd_get_mobile_code($mobile,$expire_time){
    if(empty($mobile)) return false;
    $mobile_code_log_model=M('MobileCodeLog');
    $current_time=time();
    $expire_time=(!empty($expire_time)&&$expire_time>$current_time) ? $expire_time:$current_time+60*30;
    $max_count=5;
    $find_log=$mobile_code_log_model->where(array('mobile'=>$mobile))->find();
    $result = false;
    if(empty($find_log)){
        $result = true;
    }else{
        $send_time=$find_log['send_time'];
        $today_start_time= strtotime(date('Y-m-d',$current_time));
        if($send_time<$today_start_time){
            $result = true;
        }else if($find_log['count']<$max_count){
            $result=true;
        }
    }
    
    if($result){
        $result=rand(100000,999999);
        session('mobile_code',array(
            'code'=>md5($mobile.$result.C('AUTHCODE')),
            'expire_time'=>$expire_time
        ));
    }else{
        session('mobile_code',null);
    }
    return $result;
}

/**
 * 更新手机验证码发送日志
 * @param string $mobile
 */
function jsd_mobile_code_log($mobile,$code,$expire_time){
    
    $mobile_code_log_model=M('sms_log');
    $find_log = $mobile_code_log_model->where(array('mobile'=>$mobile))->find();
    if($find_log){
        $sendtime   = strtotime(date("Y-m-d"));//当天0点
        if($find_log['send_time']<=$sendtime){
            $count =1;
        }else{
            $count = array('exp','count+1');
        }
        $result=$mobile_code_log_model->where(array('mobile'=>$mobile))->save(array('send_time'=>time(),'expire_time'=>$expire_time,'code'=>$code,'count'=>$count));
    }else{
        $result=$mobile_code_log_model->add(array('mobile'=>$mobile,'send_time'=>time(),'code'=>$code,'count'=>1,'expire_time'=>$expire_time));
    }
    
    return $result;
}


/**
 * 时间显示
 * @param  [type] $time [description](0-10)分钟  刚刚; (10-60)分钟  X分钟前; (1-24)小时 X小时前; (1-7)天  X天前； （7天以后） XX-XX-XX
 * @return [type]       [description]
 */
function timeShow($time = NULL) {
    $text = '';
    $time = $time === NULL || $time > time() ? time() : intval($time);
    $t = time() - $time; //时间差 （秒）
    switch($t){
     case $t < 60*10:
       $text = '刚刚';
       break;
     case $t < 60 * 60:
      $text = floor($t / 60) . '分钟前'; //一小时内
      break;
     case $t < 60 * 60 * 24:
      $text = floor($t / (60 * 60)) . '小时前'; // 一天内
      break;
     case $t < 60 * 60 * 24 * 7:
      $text = floor($t/(60*60*24)). '天前'; //一周内
      break;
     default:
      $text = date('Y-m-d', $time); //一年以前
      break;
    }
        
    return $text;
}

//截取字符串无乱码
function mbsubstr($str, $start=0, $length, $suffix=true, $charset="utf-8") {
	$re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	$re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	$re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	preg_match_all($re[$charset], $str, $match);
	$str=$match[0];
	$strArrCount = count($str);
	
	if($strArrCount == $length+1){
		$length += 1;
	}
	
	$slice = implode('',array_slice($str,$start,$length));
	if($strArrCount > $length){
		return $suffix ? $slice.'...' : $slice;
	}else{
		return $slice;
	}
}


//获取用的ip地址
function getIp(){
    static $realip;
    if (isset($_SERVER)){
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
            $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $realip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $realip = $_SERVER["REMOTE_ADDR"];
        }
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")){
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else {
            $realip = getenv("REMOTE_ADDR");
        } 
    }
    return $realip;
}

/**
 * +-------------------------------------------------
 * + 截取字符串长度
 * +-------------------------------------------------
 * + @param string $sourcestr 要被截取的字符串
 * + @param int $cutlength 截取的长度
 * +-------------------------------------------------
 * + @return string
 * +-------------------------------------------------
 */
function COM_CutStr( $sourcestr, $cutlength = 10) {
	$returnstr = "";
	$i = 0;
	$n = 0;
	$str_length = strlen ( $sourcestr );
	// 字符串的字节数
	while ( ($n < $cutlength) and ($i <= $str_length) ) {
		$temp_str = substr ( $sourcestr, $i, 1 );
		$ascnum = Ord ( $temp_str );
		// 得到字符串中第$i位字符的ascii码
		// 如果ASCII位高与224，
		if ($ascnum >= 224) {
			$returnstr .= substr ( $sourcestr, $i, 3 );
			// 根据UTF-8编码规范，将3个连续的字符计为单个字符
			$i = $i + 3;
			// 实际Byte计为3
			$n ++; // 字串长度计1
			// 如果ASCII位高与192，
		} elseif ($ascnum >= 192) {
			$returnstr = $returnstr . substr ( $sourcestr, $i, 2 );
			// 根据UTF-8编码规范，将2个连续的字符计为单个字符
			$i = $i + 2;
			// 实际Byte计为2
			$n ++; // 字串长度计1
			// 如果是大写字母，
		} elseif ($ascnum >= 65 && $ascnum <= 90) {
			$returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
			$i = $i + 1;
			// 实际的Byte数仍计1个
			$n ++; // 但考虑整体美观，大写字母计成一个高位字符
		} else { // 其他情况下，包括小写字母和半角标点符号，
			$returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
			$i = $i + 1;
			// 实际的Byte数计1个
			$n = $n + 0.5; // 小写字母和半角标点等与半个高位字符宽…
		}
	}
	if ($str_length > $i) {
		$returnstr .= "...";
			
		// 超过长度时在尾处加上省略号
	}
	return $returnstr;
}

/**
 * +-------------------------------------------------
 * + 去除HTML JS CSS
 * +-------------------------------------------------
 * + @param string $string 需要处理的字符串
 * +-------------------------------------------------
 * + @return string 纯文本字符串
 * +-------------------------------------------------
 */
function COM_noHtml($string) {
	if (empty ( $string )) {
		return "";
	}
	$search = array (
			"'<script[^>]*?>.*?</script>'si",
			"'<style[^>]*?>.*?</style>'si",
			"'<[/!]*?[^<>]*?>'si",
			"'<!--[/!]*?[^<>]*?>'si"
	);
	$replace = array (
			"",
			"",
			"",
			""
	);
	$string = preg_replace ( $search, $replace, $string );
	return str_replace ( array (
			"　",
			" ",
			"\r",
			"\n",
			"&nbsp;"
	), "", $string );
}

function returnMsg($array = array()) {
	$default ['status'] = 0;
	$default ['info'] = '非法操作';
	$default ['url'] = '';
	return array_merge ( $default, $array );
}

/**
 * +-------------------------------------------------
 * + 分析返回用户操作系统名称
 * +-------------------------------------------------
 * + @return string
 * +-------------------------------------------------
 */
function getSystem() {
	$sys = $_SERVER ['HTTP_USER_AGENT'];
	if (stripos ( $sys, "NT 10.0" )) {
		$os = "Windows 10";
	} elseif (stripos ( $sys, "NT 6.1" )) {
		$os = "Windows 7";
	} elseif (stripos ( $sys, "NT 6.0" )) {
		$os = "Windows Vista";
	} elseif (stripos ( $sys, "NT 5.1" )) {
		$os = "Windows XP";
	} elseif (stripos ( $sys, "NT 5.2" )) {
		$os = "Windows Server 2003";
	} elseif (stripos ( $sys, "NT 5" )) {
		$os = "Windows 2000";
	} elseif (stripos ( $sys, "NT 4.9" )) {
		$os = "Windows ME";
	} elseif (stripos ( $sys, "NT 4" )) {
		$os = "Windows NT 4.0";
	} elseif (stripos ( $sys, "98" )) {
		$os = "Windows 98";
	} elseif (stripos ( $sys, "95" )) {
		$os = "Windows 95";
	} elseif (stripos ( $sys, "Mac" )) {
		$os = "Mac";
	} elseif (stripos ( $sys, "Linux" )) {
		$os = "Linux";
	} elseif (stripos ( $sys, "Unix" )) {
		$os = "Unix";
	} elseif (stripos ( $sys, "FreeBSD" )) {
		$os = "FreeBSD";
	} elseif (stripos ( $sys, "SunOS" )) {
		$os = "SunOS";
	} elseif (stripos ( $sys, "BeOS" )) {
		$os = "BeOS";
	} elseif (stripos ( $sys, "OS/2" )) {
		$os = "OS/2";
	} elseif (stripos ( $sys, "PC" )) {
		$os = "Macintosh";
	} elseif (stripos ( $sys, "AIX" )) {
		$os = "AIX";
	} else {
		$os = "未知操作系统";
	}
	return $os;
}

/**
 * +-------------------------------------------------
 * + 分析返回用户网页浏览器名称
 * +-------------------------------------------------
 * + @return string
 * +-------------------------------------------------
 */
function getBrowser() {
	global $_SERVER;
	$agent = $_SERVER ['HTTP_USER_AGENT'];
	$browser = '';
	$browser_ver = '';
	if (preg_match ( '/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs )) {
		$browser = 'OmniWeb';
		$browser_ver = $regs [2];
	}
	if (preg_match ( '/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs )) {
		$browser = 'Netscape';
		$browser_ver = $regs [2];
	}
	if (preg_match ( '/safari\/([^\s]+)/i', $agent, $regs )) {
		$browser = 'Safari';
		$browser_ver = $regs [1];
	}
	if (preg_match ( '/MSIE\s([^\s|;]+)/i', $agent, $regs )) {
		$browser = 'Internet Explorer';
		$browser_ver = $regs [1];
	}
	if (preg_match ( '/Opera[\s|\/]([^\s]+)/i', $agent, $regs )) {
		$browser = 'Opera';
		$browser_ver = $regs [1];
	}
	if (preg_match ( '/NetCaptor\s([^\s|;]+)/i', $agent, $regs )) {
		$browser = '(Internet Explorer ' . $browser_ver . ') NetCaptor';
		$browser_ver = $regs [1];
	}
	if (preg_match ( '/Maxthon/i', $agent, $regs )) {
		$browser = '(Internet Explorer ' . $browser_ver . ') Maxthon';
		$browser_ver = '';
	}
	if (preg_match ( '/FireFox\/([^\s]+)/i', $agent, $regs )) {
		$browser = 'FireFox';
		$browser_ver = $regs [1];
	}
	if (preg_match ( '/Lynx\/([^\s]+)/i', $agent, $regs )) {
		$browser = 'Lynx';
		$browser_ver = $regs [1];
	}
	if ($browser != '') {
		return $browser . ' ' . $browser_ver;
	} else {
		return 'Unknow browser';
	}
}

/**
 * +-------------------------------------------------
 * + 返回一个数组
 * +-------------------------------------------------
 * + @param array
 * +-------------------------------------------------
 * + @return string
 * +-------------------------------------------------
 */
function returnArray($array = array()) {
	if (count ( $array ) == false) {
		$array = array (
				'status' => '1',
				'info' => '操作成功!'
		);
	}
	return $array;
}


/**
 * 防止sql注入
 *
 * @param ) $sql_str 参入参数
 * @return 真假判断
 *
 **/
function inject_check($sql_str) { 
	return eregi('select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str);
}

function create_guid() {
    $charid = strtoupper(md5(uniqid(mt_rand(), true)));
    $hyphen = chr(45);
	$uuid = substr($charid, 0, 8).$hyphen
    .substr($charid, 8, 4).$hyphen
    .substr($charid,12, 4).$hyphen
    .substr($charid,16, 4).$hyphen
	.substr($charid,20,12);
    return $uuid;
}